package no.uio.inf5750.j2mewsclient;

import java.io.IOException;
import java.io.InputStream;

import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.TextBox;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;

public class SimpleMIDlet extends MIDlet implements CommandListener {

    private Command cmd_exit;

    private static Display display;

    private Form form;

    public void startApp() throws MIDletStateChangeException {

        display = Display.getDisplay(this);
        form = new Form("Simple");
        form.setCommandListener(this);
        
		try {
			openConnection( "http://www.webservicex.net/ConvertTemperature.asmx?op=ConvertTemp" );
		} catch (IOException e) {
			//e.printStackTrace();
			System.out.println( "Sorry, couldn't connect!");
		}
						
        System.out.println("Starting app");

        cmd_exit = new Command("Exit", Command.EXIT, 0);
        form.addCommand(cmd_exit);

        form.append("Hello j2me");

        Runtime rt = Runtime.getRuntime();
        form.append("Free Memory: " + rt.freeMemory());
        form.append("Total Memory: " + rt.totalMemory());

        display.setCurrent(form);
    }

    public void pauseApp() {

    }

    public void destroyApp(boolean unconditional) throws MIDletStateChangeException {
        notifyDestroyed();
    }

    public void commandAction(Command c, Displayable d) {
        if (c == cmd_exit) {
            try {
                destroyApp(true);
            } catch (MIDletStateChangeException e) {
                showException(e);
            }
        }
    }

    public void showException(Exception e) {
        Alert alert = new Alert("Error");
        alert.setString(e.getMessage());
        alert.setType(AlertType.ERROR);
        alert.setTimeout(Alert.FOREVER);
        display.setCurrent(alert);
    }
    
    public void openConnection(final String url) 
  	throws IOException {
    	HttpConnection c = null; 
    	StringBuffer b = new StringBuffer();
    	InputStream is = null;    
    	TextBox t = null;
    
    	try {
    		long len = 0 ;
    		int ch = 0;
    		c = (HttpConnection)Connector.open(url);
    		//c.setRequestMethod( HttpConnection.POST);
    		System.out.println( "Protocol: " + c.getProtocol() );
    		is = c.openInputStream();
    		len =c.getLength();
    		if( len != -1) {
    			// Read exactly Content-Length bytes
    			for(int i = 0 ; i < len ; i++ )
    			{
    				if((ch = is.read()) != -1) {
    					b.append((char) ch);
    				}
    			}
    		} else {
    			//Read until the connection is closed.
    			while ((ch = is.read()) != -1) {
    				len = is.available() ;
    				b.append((char)ch);
    			}
    		}
    		t = new TextBox("hello again....", b.toString(), 1024, 0);
    		//form.append( b.toString() );
    	} finally {
    		is.close();
    		c.close();
    	}
    	display.setCurrent( t );
    }
}
